using System;
using System.Collections;
using UnityEngine.Networking;
using Voodoo.Sauce.Internal.CrossPromo.Mercury.Models;

namespace Voodoo.Sauce.Internal.CrossPromo.Mercury
{
	public static class MercuryDownloader
	{
		private const string TAG = "MercuryDownloader";

		public static void DownloadWaterfall(MercuryWaterfall waterfall, Action<MercuryPromotedAsset> onAssetDownloaded, bool overrideCache)
		{
			for (int i = 0; i < waterfall.promote_assets.Length; i++)
			{
				MercuryPromotedAsset asset3 = waterfall.promote_assets[i];
				asset3.videoIndex = i;
				if (overrideCache || !MercuryCache.IsCached(asset3.id))
				{
					DownloadVideo(asset3, delegate(MercuryPromotedAsset asset2, byte[] data)
					{
						OnVideoDownloaded(asset2, data);
						onAssetDownloaded?.Invoke(MercuryCache.GetAsset(asset3.id));
					});
				}
				else
				{
					VoodooLog.LogDebug(Module.CROSS_PROMO, "MercuryDownloader", "Get video from cache: " + asset3.id);
					MercuryPromotedAsset asset4 = MercuryCache.GetAsset(asset3.id);
					onAssetDownloaded?.Invoke(asset4);
				}
			}
		}

		private static void OnVideoDownloaded(MercuryPromotedAsset asset, byte[] bytes)
		{
			MercuryCache.SaveAsset(asset, bytes);
		}

		private static void DownloadVideo(MercuryPromotedAsset asset, Action<MercuryPromotedAsset, byte[]> onSuccess)
		{
			MercuryAPI.Instance.StartCoroutine(DownloadVideoCoroutine(asset, onSuccess));
		}

		private static IEnumerator DownloadVideoCoroutine(MercuryPromotedAsset asset, Action<MercuryPromotedAsset, byte[]> onSuccess)
		{
			string videoUrl = asset.file_url;
			UnityWebRequest webRequest = UnityWebRequest.Get(videoUrl);
			yield return webRequest.SendWebRequest();
			if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
			{
				VoodooLog.LogWarning(Module.CROSS_PROMO, "MercuryDownloader", "Couldn't download video: " + videoUrl);
				yield break;
			}
			VoodooLog.LogDebug(Module.CROSS_PROMO, "MercuryDownloader", "Downloaded video: " + videoUrl);
			onSuccess?.Invoke(asset, webRequest.downloadHandler.data);
		}
	}
}
